import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {SYS_ENUMS} from "@/utils/constants";
import {DictionaryManager, Marketing} from "@/services/api-functions";
import {isSuccess} from "@/utils/utils";
import {Button, Form, message, Modal, Tag} from "antd";
import {
  ModalForm,
  ProFormDateTimeRangePicker,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea
} from "@ant-design/pro-form";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons";

export const welfareDelete = async (select: any) => {
  if (!select) return false;
  try {
    message.loading('正在删除');
    if (isSuccess((await Marketing.welfareDel(select.id))?.code)) {
      message.success('删除成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};
export const welfareAdd = async (fields: any) => {
  try {
    if (isSuccess((await Marketing.welfareAdd({
      effectiveEndTime: fields.timeRange[1]??'',
      effectiveNum: fields.effectiveNum,
      effectiveStartTime: fields.timeRange[0]??'',
      remark: fields.remark,
      title: fields.title,
      welfareType: fields.welfareType,
      memberWelfare: {
        effectiveDay: fields.effectiveDay??7
      }
    }))?.code)) {
      message.success('添加成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};

const WelfareList: React.FC<any> = (props) => {
  const [auditFormRef] = Form.useForm()
  const actionRef = useRef<ActionType>();
  const [auditVisible, handleAuditVisible] = useState<boolean>(false);
  const BASE_COLUMNS: ProColumns[] = [
    {
      title: '优惠码',
      dataIndex: 'welfareCode',
      fixed: 'left'
    },
    {
      title: '标题',
      dataIndex: 'title',
      fixed: 'left'
    },
    {
      title: '福利类型',
      dataIndex: 'welfareType',
      valueEnum: SYS_ENUMS.WELFARE_TYPE,
      width: 100,
      hideInForm: true,
    },
    {
      title: '领取个数',
      dataIndex: 'acquireNum',
      width: 100,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '有效个数',
      dataIndex: 'effectiveNum',
      width: 100,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '生效开始时间',
      dataIndex: 'effectiveStartTime',
      ellipsis: true,
      hideInSearch: true,
      width: 150,
    },
    {
      title: '生效结束时间',
      dataIndex: 'effectiveEndTime',
      ellipsis: true,
      hideInSearch: true,
      width: 150,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      fixed: 'right',
      render: (_, record) => [
        <a key="edit" style={{color: "red"}}
           onClick={() => Modal.confirm({
             title: '提示',
             icon: <ExclamationCircleOutlined/>,
             content: <span>确定要删除 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
             okText: '删除',
             cancelText: '取消',
             onOk: async () => {
               if (await welfareDelete(record)) {
                 actionRef.current?.reload()
               }
             },
           })}
        >删除</a>,
      ],
    },
  ]
  return (
    <PageContainer>
      <ProTable<any, any>
        actionRef={actionRef}
        rowKey="key"
        search={{labelWidth: 120,}}
        request={async (params) => {
          const {data: {data, total}, code}: any = await Marketing.welfarePageQuery(params)
          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => handleAuditVisible(true)}>
            <PlusOutlined/> 新建
          </Button>
        ]}
        columns={BASE_COLUMNS}
        scroll={{x: 1300}}
      />
      <ModalForm
        title='添加福利码'
        width="750px"
        form={auditFormRef}
        visible={auditVisible}
        onVisibleChange={v => {
          handleAuditVisible(v)
          if (!v) {
            auditFormRef?.resetFields()
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await welfareAdd(value as any)) {
            handleAuditVisible(false);
            auditFormRef?.resetFields()
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText label='福利标题' name='title' required />
        <ProFormDigit label='有效个数' name='effectiveNum' min={1} fieldProps={{ precision: 0 }} required />
        <ProFormSelect label='福利类型' required rules={[{required: true, message: '请填选择福利类型',},]} name='welfareType'
                       initialValue={SYS_ENUMS.WELFARE_TYPE.EXPERIENCE_MEMBER.value} options={[
          {label: SYS_ENUMS.WELFARE_TYPE.EXPERIENCE_MEMBER.label, value: SYS_ENUMS.WELFARE_TYPE.EXPERIENCE_MEMBER.value},
        ]}/>
        <ProFormDateTimeRangePicker label='生失效时间' name='timeRange' required/>
        <ProFormSelect label='体验会员天数' name='effectiveDay' required rules={[{required: true, message: '请设置体验会员天数',},]}
                       request={async (params) => {
                         const {code, data} = await DictionaryManager.detail({
                           current: 1,
                           pageSize: 20,
                           enabling: 1,
                           parentKey: 'MEMBER_WELFARE',
                           name: params.keyWords ?? '',
                         })
                         return [{label: `暂无`, value: '0'}, ...(isSuccess(code) ? (data ?? []).map((item: any) => {
                           const {name, key} = item
                           return {label: `${name}(${key})`, value: key}
                         }) : [])]
                       }} showSearch/>
        <ProFormTextArea label='备注' name="remark"/>
      </ModalForm>
    </PageContainer>
  );
};

export default WelfareList;
